/**
 * 
 */
package jmine.tec.report.impl;

import java.util.List;
import java.util.Map;

import jmine.tec.report.DataRow;
import jmine.tec.report.ExecutableDataRow;
import jmine.tec.report.cell.impl.PercentageDataCell;

/**
 * @author takeshi
 * @version 23/08/2007
 */
public class PercentageDataColumn extends AbstractExecutableDataColumn {

    private static final long serialVersionUID = -1529786196319640947L;

    /**
     * C'tor
     * 
     * @param key the column key
     * @param name the column name
     */
    public PercentageDataColumn(final String key, final String name) {
        super(key, name);
    }

    /**
     * @param row the row
     * @param index the index
     */
    private void calculatePercentages(final ExecutableDataRow row, final int index) {
        final List<? extends DataRow> children = row.getChildRows();
        double total = 0;
        for (DataRow dataRow : children) {
            total += dataRow.getCell(index).toDouble().doubleValue();
        }
        for (DataRow dataRow : children) {
            final double val = dataRow.getCell(index).toDouble().doubleValue();
            if (dataRow.getCellCount() > index + 1) {
                // this row was executed 2x
                dataRow.removeCellWithIndex(index + 1);
            }
            final PercentageDataCell cell = new PercentageDataCell(val / total);
            dataRow.addCell(cell);
        }
    }

    /**
     * @param row the row
     * @param params the params
     */
    @Override
    protected void executeDefaultRow(final ExecutableDataRow row, final Map<String, Object> params) {
        if (row.getChildRows().isEmpty()) {
            row.addCell(this.getEmptyDataCell());
        } else {
            this.recurseChildRows(row, params);
            int index = row.getCellCount() - 1;
            if (index < 0) {
                row.addCell(this.getEmptyDataCell());
            } else {
                this.calculatePercentages(row, index);
                row.addCell(this.getEmptyDataCell());
            }
        }
    }

}
